package com.xnck.example.jertest.interceptor;

import com.xnck.example.jertest.annotation.AuthenPassport;
import com.xnck.example.jertest.constant.ContextConstant;
import com.xnck.example.jertest.util.ResponseUtil;
import com.xnck.example.jertest.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    protected static final Logger log = Logger.getLogger(LoginInterceptor.class);

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) throws Exception {

    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果拦截的是方法，查验是否有AuthenPassport注解，如果有注解则需要验证用户是否已登录
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod)handler;
            AuthenPassport authPassport = method.getMethodAnnotation(AuthenPassport.class);
            if (authPassport == null || authPassport.validate() == false) {
                return true;
            }
            String token = request.getParameter(ContextConstant.KEY_TOKEN);
            if (StrUtil.isBlank(token)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put(ContextConstant.KEY_CODE, ContextConstant.VALUE_SESSION_OUT);
                map.put(ContextConstant.KEY_MSG, "登录已超时");
                ResponseUtil.responseJSON(map);
                return false;
            }
        }
        return true;
    }
}
